<template>
	<view class="page">
		<view class="student">
			<view class="title"><text>学生样本对比结果</text></view>

			<view class="title">
				<text>当前比对样本: {{ currentSampleName }}</text>
			</view>

			<view class="sample">
				<view class="u-m-b-20"><text>请选择要比对的样本:</text></view>
				<scroll-view class="sample-scroll" scroll-x scroll-with-animation>
					<view class="sample-scroll-box">
						<view
							class="sample-scroll-box-item"
							:class="[index === currentSampleIndex ? 'active' : '']"
							v-for="(item, index) in sampleImgList"
							:key="item._id"
							@tap="chooseCurrentSample(index)"
						>
							<image class="img" :src="item.url"></image>
							<text class="name">{{ item.name }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<view class="compare">
				<uni-file-picker
					ref="imgCompare"
					v-model="imageVal"
					:limit="sampleImgList.length"
					title="学生上传对比样本"
					fileMediatype="image"
					mode="grid"
					@success="onImgUploadSuccess"
				/>
				<!-- <view v-if="compareImgList.length" class="compare-list">
					<image class="compare-img" :src="item" v-for="(item, index) in compareImgList" :key="index" @tap="compareImage('update', index)"></image>
				</view>
				<view v-if="showAddBtn" class="compare-add"><uni-icons type="plusempty" size="64" color="#dadbde" @click="compareImage('add', '')"></uni-icons></view> -->
			</view>

			<view v-if="compareRes.length" class="result-list">
				<text v-for="(item, index) in compareRes" :key="index">第{{ index + 1 }}次比对结果: {{ item }}</text>
				<text v-if="showFinalResult">{{ compareResAvgStr }}</text>
			</view>
		</view>

		<i-button shape="circle" width="500rpx" height="80rpx" margin="30rpx auto" @click="navToResult">查看对比结果</i-button>

		<uni-fab horizontal="right" vertical="bottom" :popMenu="false" :pattern="{ icon: 'chat' }" @fabClick="onFabClick" />
	</view>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'

const imageVal = ref({})
const imgCompare = ref(null)

const currentSampleIndex = ref(0)
const currentSampleName = ref('样本1')
const sampleImgList = ref([])
const compareImgList = ref([])
const compareRes = ref([])

const compareResAvg = computed(() => {
	const len = compareRes.value.length
	const total = compareRes.value.reduce((acc, c) => {
		acc = acc + c
		return acc
	}, 0)
	const avg = Math.round((total / len) * 100)
	return `${avg}%`
})

const compareResAvgStr = computed(() => {
	return `上传样本最终相似度平均值为${compareResAvg.value}`
})

const showFinalResult = computed(() => sampleImgList.value.length === compareRes.value.length)

onLoad(() => {
	getSample()
})

onReady(() => {})

const onFabClick = () => {
	const url = `/pages/chat/chat`
	uni.navigateTo({
		url
	})
}

const navToResult = () => {
	const url = `/pages/student/list/index2`
	uni.navigateTo({
		url
	})
}

const getSample = async () => {
	const sample = uniCloud.importObject('sample')
	try {
		const res = await sample.get()
		console.log(res)
		sampleImgList.value = res.data
	} catch (e) {
		console.log(e.errMsg)
	}
}

const chooseCurrentSample = val => {
	currentSampleIndex.value = val
	currentSampleName.value = sampleImgList.value[val].name
}

const addCompareRes = async () => {
	const compare = uniCloud.importObject('compare')
	try {
		const res = await compare.add({
			score: compareResAvg.value
		})
		console.log(res)
	} catch (e) {
		console.log(e.errMsg)
	}
}

const getCompareScore = async (url1, url2) => {
	const compare = uniCloud.importObject('compare')
	try {
		const res = await compare.compareImgByHash({
			url1,
			url2
		})
		console.log(res)
		return res
	} catch (e) {
		console.log(e.errMsg)
	}
}

const onImgUploadSuccess = async e => {
	console.log('onImgUploadSuccess: ', e)
	const paths = e.tempFilePaths
	const url1 = paths[0]
	const url2 = sampleImgList.value[currentSampleIndex.value].url
	const score = await getCompareScore(url1, url2)
	compareRes.value[currentSampleIndex.value] = score
	compareRes.value = compareRes.value.filter(Boolean)

	if (currentSampleIndex.value < sampleImgList.value.length - 1) {
		currentSampleIndex.value += 1
		currentSampleName.value = sampleImgList.value[currentSampleIndex.value].name
	}

	if (showFinalResult.value) {
		addCompareRes()
	}
}

const compareImage = (type, index) => {
	uni.chooseMedia({
		count: 1,
		mediaType: ['image'],
		sourceType: ['album', 'camera'],
		success: res => {
			console.log(res.tempFiles)
			const paths = res.tempFiles.map(_ => _.tempFilePath)
			const path1 = paths[0]
			const path2 = sampleImgList.value.find(_ => _.name === currentSample.value).url
			console.log(path1, path2)
			if (type === 'add') {
				const i = +currentSample.value.slice(-1)
				compareImgList.value[i - 1] = paths[0]
				getCompareScore(path1, path2, i - 1)
			} else {
				compareImgList.value[index] = paths[0]
				getCompareScore(path1, path2, index)
			}
			if (compareImgList.value.length === sampleImgList.value.length) {
				addCompareRes()
			}
		}
	})
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
